package com.auth.manager.common.global;

import com.auth.manager.common.ex.ApiException;
import com.auth.manager.common.ex.BizException;
import com.auth.manager.common.resp.Result;
import com.auth.manager.common.resp.ResultEnum;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * @version 1.0.0
 * @Date: 2022/4/27 15:38
 * @Author ZhuYouBin
 * @Description 全局异常处理, 当控制Controller抛出异常时候, 会被全局异常处理器捕获到, 从而我们可以自定义处理异常
 */
@ControllerAdvice // 这个注解作用: 就是通过Aop切面当所有的Controller发生异常时候，可以执行异常通知
public class GlobalExceptionHandler {

    /***************************** Biz exception ******************************/
    @ExceptionHandler(BizException.class)
    @ResponseBody
    public Result handlerBizException(BizException e) {
        e.printStackTrace();
        return Result.failed(e.getMessage());
    }

    /***************************** Api exception ******************************/
    @ExceptionHandler(ApiException.class)
    @ResponseBody
    public Result handlerApiException(ApiException e) {
        e.printStackTrace();
        return Result.failed(e.getMessage());
    }

    /***************************** method parameter valid exception ******************************/
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public Result handlerMethodParameterException(MethodArgumentNotValidException e) {
        e.printStackTrace();
        // 保存错误提示信息
        StringBuilder builder = new StringBuilder();
        // 从异常对象中拿到 ObjectError 对象
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        if (allErrors.size() > 0) {
            ObjectError objectError = allErrors.get(0);
            builder.append(objectError.getDefaultMessage());
        }
        ResultEnum resultEnum = ResultEnum.METHOD_PARAMETER;
        resultEnum.setMessage(builder.toString());
        return Result.failed(resultEnum);
    }

    /***************************** method parameter valid exception ******************************/
    @ExceptionHandler(HttpMessageNotReadableException.class)
    @ResponseBody
    public Result handlerMessageException(HttpMessageNotReadableException e) {
        e.printStackTrace();
        return Result.failed(e.toString());
    }

    /***************************** common exception ******************************/
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result handlerException(Exception e) {
        e.printStackTrace();
        return Result.failed("系统异常，请联系管理员！");
    }

}
